package com.ics.atable.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ics.atable.chat.expection.ErrorCode;
import com.ics.atable.chat.expection.ThrowUtils;
import com.ics.atable.chat.mapper.ChatMessageMapper;
import com.ics.atable.chat.model.entity.ChatMessage;
import com.ics.atable.chat.model.enums.ResponseTypeEnum;
import com.ics.atable.chat.model.vo.history.ChatHistoryVO;
import com.ics.atable.chat.model.vo.node.stream.StringStreamResponse;
import com.ics.atable.chat.service.ChatMessageService;
import com.ics.atable.chat.serializer.ChatContentCodec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天消息服务实现
 *
 * @author haohongbin
 */
@Slf4j
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage>
    implements ChatMessageService {

    private final ChatContentCodec chatContentCodec;

    public ChatMessageServiceImpl(ChatContentCodec chatContentCodec) {
        this.chatContentCodec = chatContentCodec;
    }

    @Override
    public Page<ChatHistoryVO> listChatHistory(String sessionId, int pageSize, LocalDateTime lastCreateTime) {

        ThrowUtils.throwIf(StringUtils.isEmpty(sessionId), ErrorCode.PARAMS_ERROR, "应用ID不能为空");
        ThrowUtils.throwIf(pageSize <= 0 || pageSize > 50, ErrorCode.PARAMS_ERROR, "页面大小必须在1-50之间");

        // 构造查询条件
        LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessage::getSessionId, sessionId);

        // 如果lastCreateTime不为null，则查询该时间之前的消息
        // 如果lastCreateTime不为null，则查询该时间之前的消息
        if (lastCreateTime != null) {
            queryWrapper.lt(ChatMessage::getCreateTime, lastCreateTime);
        }

        queryWrapper.orderByDesc(ChatMessage::getCreateTime);

        // 使用第一页，因为是基于时间戳的分页而不是页码分页
        Page<ChatMessage> page = new Page<>(1, pageSize);
        Page<ChatMessage> resultPage = this.page(page, queryWrapper);

        // 手动创建新的 Page<ChatHistoryVO> 对象
        Page<ChatHistoryVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        voPage.setRecords(resultPage.getRecords().stream()
                .map(this::convertToChatHistoryVO)
                .toList());

        return voPage;
    }

    @Override
    public int loadChatHistoryToMemory(String sessionId, ChatMemory chatMemory, int maxCount) {
        try {
            LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatMessage::getSessionId, sessionId)
                    .orderByDesc(ChatMessage::getCreateTime);
            List<ChatMessage> historyList = this.list(queryWrapper);
            if (CollectionUtils.isEmpty(historyList)) {
                return 0;
            }
            // 反转列表，保证时间正序
            historyList = historyList.reversed();
            // 按时间顺序添加到记忆中
            int loadedCount = 0;
            // 先清理历史缓存，防止重复加载
            chatMemory.clear(sessionId);
            List<Message> messageList = new ArrayList<>();
            for (ChatMessage history : historyList) {
                if (MessageType.USER.getValue().equals(history.getMessageType())) {
                    messageList.add(new UserMessage(history.getContent()));
                    loadedCount++;
                } else if (MessageType.ASSISTANT.getValue().equals(history.getMessageType())) {
                    messageList.add(new AssistantMessage(history.getContent()));
                    loadedCount++;
                }
            }
            log.info("成功为 sessionId: {} 加载了 {} 条历史对话", sessionId, loadedCount);
            return loadedCount;
        } catch (Exception e) {
            log.error("加载历史对话失败，sessionId: {}, error: {}", sessionId, e.getMessage(), e);
            // 加载失败不影响系统运行，只是没有历史上下文
            return 0;
        }
    }

    /**
     * 将ChatMessage转换为ChatHistoryVO
     * @param message 聊天消息实体
     * @return 聊天历史VO
     */
    private ChatHistoryVO convertToChatHistoryVO(ChatMessage message) {
        if (MessageType.ASSISTANT.getValue().equals(message.getRole())) {
            return convertToStreamResponse(message);
        } else {
            ChatHistoryVO chatHistoryVO = new ChatHistoryVO();
            chatHistoryVO.setMessageId(message.getId());
            chatHistoryVO.setSessionId(message.getSessionId());
            chatHistoryVO.setRole(message.getRole());
            chatHistoryVO.setContent(message.getContent()); // user消息保持为String
            chatHistoryVO.setMessageType(message.getMessageType());
            chatHistoryVO.setMetadata(message.getMetadata());
            chatHistoryVO.setCreateTime(message.getCreateTime());
            return chatHistoryVO;
        }
    }

    private ChatHistoryVO convertToStreamResponse(ChatMessage message) {
        ChatHistoryVO chatHistoryVO = new ChatHistoryVO();
        if (ResponseTypeEnum.NODE_OBJECT.getCode().equals(message.getMessageType())) {
            chatHistoryVO.setMessageId(message.getId());
            chatHistoryVO.setSessionId(message.getSessionId());
            chatHistoryVO.setRole(message.getRole());
            chatHistoryVO.setContent(chatContentCodec.deserializeObjectStreamResponse(message.getContent())); // assistant消息根据类型处理
            chatHistoryVO.setMessageType(message.getMessageType());
            chatHistoryVO.setMetadata(message.getMetadata());
            chatHistoryVO.setCreateTime(message.getCreateTime());
        } else {
            chatHistoryVO.setMessageId(message.getId());
            chatHistoryVO.setSessionId(message.getSessionId());
            chatHistoryVO.setRole(message.getRole());
            chatHistoryVO.setContent(new StringStreamResponse(message.getContent())); // assistant消息根据类型处理
            chatHistoryVO.setMessageType(message.getMessageType());
            chatHistoryVO.setMetadata(message.getMetadata());
            chatHistoryVO.setCreateTime(message.getCreateTime());
        }
        return chatHistoryVO;
    }



}